<template>
  <div class="form-container">
    <el-form inline :model="form" ref="ruleForm" class="form-line" label-width="70">
      <el-form-item label="设施类型" prop="facilityTypeId">
        <el-select @change="getDeviceList" v-model="form.facilityTypeId" placeholder="请选择设施类型">
          <el-option
            v-for="item in deviceTypeList as DeviceType.Post[]"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-container">
      <el-button type="primary" @click="handleReset(ruleForm as FormInstance)">重置</el-button>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="primary" @click="handleAdd()">添加</el-button>
    </div>
  </div>
  <div class="table-container">
    <el-table
      border
      :cell-style="{ textAlign: 'center', fontSize: '13px' }"
      :header-cell-style="{
        textAlign: 'center',
        fontWeight: '100',
        fontSize: '13px',
        color: 'white',
        backgroundColor: '#009688'
      }"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column fixed prop="facilityTypeName" label="设施类型" />
      <el-table-column prop="amount" label="合计数量" />
      <el-table-column prop="updateTime" label="添加/修改时间" />
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(scope.row.id)"> 修改 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="pagination-container">
      <el-pagination
        background
        size="small"
        v-model:current-page="form.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        layout="prev, pager, next"
        :total="50"
        :page-size="form.pageSize"
      />
    </div> -->
  </div>
  <el-dialog v-model="centerDialogVisible" :title="modalTitle" width="500" destroy-on-close center>
    <div style="text-align: center">
      <el-form ref="ruleAddForm" :model="addForm" :rules="addRules" label-width="80px" class="demo-ruleForm">
        <el-form-item label="设施类型" prop="facilityTypeId">
          <el-select v-model="addForm.facilityTypeId" placeholder="请选择设施类型">
            <el-option
              v-for="item in deviceTypeList as DeviceType.Post[]"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施数量" prop="amount">
          <el-input v-model="addForm.amount" placeholder="请输入合计数量"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" v-if="modalTitle === '添加'" @click="handleAddForm(ruleAddForm as FormInstance)">
          添加
        </el-button>
        <el-button type="primary" v-else @click="handleUpdateForm(ruleAddForm as FormInstance)"> 修改 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="useProTable">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import {
  getDeviceListAPI,
  updateDeviceAPI,
  deviceDeleteAPI,
  addDeviceAPI,
  deviceDetailAPI,
  getDeviceTypeListAPI
} from "@/api/modules/province/organizMangeAPI";
import { Device, DeviceType } from "@/api/interface/province/organizationManage";
const route = useRoute();
let centerDialogVisible = ref(false);
//ProCompanyType 已经通过declare全局申明过不用再单独导入
let tableData = ref<Device.DeviceList[]>([]);
const form = ref<Device.DeviceSearchForm>({
  facilityTypeId: "",
  stationId: ""
});
const ruleForm = ref<FormInstance>();
let modalTitle = ref("添加");

const handleReset = (Elform: FormInstance) => {
  Elform.resetFields();
  getDeviceList();
};

const handleSearch = (): void => {
  getDeviceList();
};
const handleDelete = (id: string): void => {
  ElMessageBox.confirm(`确定删除该条记录${name}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteDevice(id);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
// 删除仓站
const deleteDevice = async (id: string) => {
  const { code, msg } = await deviceDeleteAPI(id);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "删除成功!"
    });
    getDeviceList();
  } else {
    ElMessage.error(`删除失败,${msg}`);
  }
};
// 列表接口请求地址
const getDeviceList = async () => {
  const { data, code, msg } = await getDeviceListAPI(form.value);
  if (code == "200" && data) {
    tableData.value = data;
  } else {
    ElMessage.error(`获取列表失败,${msg}`);
  }
};
const deviceTypeList = ref<DeviceType.Data | DeviceType.Post[]>();
const getDeviceTypeList = async () => {
  const { code, data } = await getDeviceTypeListAPI({
    userId: JSON.parse(localStorage.getItem("userInfo") as string).userId,
    id: route.query.id as string
  });
  if (code == "200" && data) {
    deviceTypeList.value = data;
  }
};
const addForm = ref<Device.AddDevice>({
  stationId: route.query.id as string
});
const ruleAddForm = ref<FormInstance>();
const addRules = reactive<FormRules>({
  facilityTypeId: [{ required: true, message: "请选择设施类型", trigger: "blur" }],
  amount: [
    { required: true, message: "请输入设施数量", trigger: "blur" },
    { type: "string", message: "请输入正确的设施数量", trigger: "blur" }
  ]
});
const handleAdd = (): void => {
  // Elform.resetFields();
  addForm.value = {
    stationId: route.query.id as string
  };
  modalTitle.value = "添加";
  centerDialogVisible.value = true;
};
const handleEdit = (id: string) => {
  modalTitle.value = "修改";
  centerDialogVisible.value = true;
  deviceDetail(id);
};
const handleAddForm = (formEl: FormInstance): void => {
  formEl.validate(valid => {
    console.log("验证结果", valid);
    if (valid) {
      AddForm();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const handleUpdateForm = (formEl: FormInstance): void => {
  formEl.validate(valid => {
    console.log("验证结果", valid);
    if (valid) {
      UpdateForm();
    } else {
      ElMessage.error("请检查输入项");
    }
  });
};
const AddForm = async () => {
  addForm.value.amount = Number(addForm.value.amount);
  const { code, msg } = await addDeviceAPI(addForm.value);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "添加成功!"
    });
    centerDialogVisible.value = false;
    getDeviceList();
  } else {
    ElMessage.error(`添加失败,${msg}`);
  }
};
const UpdateForm = async () => {
  addForm.value.amount = Number(addForm.value.amount);
  addForm.value.id = String(addForm.value.id);
  console.log("修改", addForm.value);
  const { code, msg } = await updateDeviceAPI(addForm.value);
  if (code == "200") {
    ElMessage({
      type: "success",
      message: "添加成功!"
    });
    centerDialogVisible.value = false;
    getDeviceList();
  } else {
    ElMessage.error(`添加失败,${msg}`);
  }
};
const deviceDetail = async (id: string) => {
  const { code, msg, data } = await deviceDetailAPI(id);
  if (code == "200" && data) {
    // addForm.value = data;
    addForm.value.facilityTypeId = Number(data.facilityTypeId);
    addForm.value.amount = Number(data.amount);
    addForm.value.id = data.id as string;
    delete addForm.value.stationId;
  } else {
    ElMessage.error(`获取列表失败,${msg}`);
  }
};
onMounted(() => {
  // if(route.query.id) companyDetail(route.query.id as number);
  console.log("路由信息", route.query);
  if (route.query.id != undefined) {
    form.value.stationId = route.query.id as string;
    getDeviceList();
    getDeviceTypeList();
  }
});
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .btn-container {
    display: inline-block;
    float: right;
    vertical-align: middle;
    ::v-deep .el-button > span {
      font-size: 13px;
    }
  }
  .el-form {
    display: inline-block;
    ::v-deep .el-form-item__label {
      font-size: 13px;
    }
  }
  .form-line {
    .el-form-item {
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  padding: 40px 10px;
  padding-bottom: 60px;
  background-color: white;
  .pagination-container {
    // display: inline-block;
    float: right;
    margin-top: 20px;
    background-color: white;
  }
}
</style>
